package middle;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class Solution_166 {

    public String fractionToDecimal(int numerator, int denominator) {
        if (numerator == 0) {
            return "0";
        }
        long numerator_new = numerator;
        boolean flag = (numerator_new >= 0 && denominator >= 0) || (numerator_new < 0 && denominator < 0);
        numerator_new = numerator_new > 0 ? -numerator_new : numerator_new;
        denominator = denominator > 0 ? -denominator : denominator;
        StringBuilder builder = new StringBuilder();
        builder.append(numerator_new / denominator);
        numerator_new = (numerator_new % denominator) * 10;

        StringBuilder decimalBuilder = new StringBuilder();
        Map<Long, Integer> map = new HashMap<>();
        while (true) {
            if (numerator_new == 0) {
                break;
            } else if (map.containsKey(numerator_new)) {
                decimalBuilder.insert(map.get(numerator_new), "(");
                decimalBuilder.append(")");
                break;
            } else {
                map.put(numerator_new, decimalBuilder.length());
                long num = numerator_new / denominator;
                decimalBuilder.append(num);
                numerator_new = (numerator_new % denominator) * 10;
            }
        }
        if (!flag) {
            builder.insert(0, "-");
        }
        if (decimalBuilder.length() > 0) {
            builder.append(".").append(decimalBuilder);
        }
        return builder.toString();
    }

    public static void main(String[] args) {
        Solution_166 model = new Solution_166();
//        System.out.println(model.fractionToDecimal(1, 2));
//        System.out.println(model.fractionToDecimal(2, 1));
//        System.out.println(model.fractionToDecimal(-2, 1));
//        System.out.println(model.fractionToDecimal(4, 333));
//        System.out.println(model.fractionToDecimal(4, -333));
//        System.out.println(model.fractionToDecimal(1, -6));
        System.out.println(model.fractionToDecimal(-1, Integer.MIN_VALUE));
    }
}
